import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem';
import axios from "axios";


class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '卧槽',
            list: ['666', '学英语', 'React', 777]
        }
    }

    render() {
        return (
            <Fragment>
                <div>
                    <label htmlFor='insertArea'>输入内容</label>
                    <input className='input' 
                        id='insertArea'
                        value={this.state.inputValue} 
                        onChange={this.handleInputChange}
                        ref={(input) => {this.input = input}}
                    />
                    <button onClick={this.addList}>提交</button>
                </div>
                <ul>
                    {this.getTodoItem()}
                </ul>
            </Fragment>
        );
    };

    componentDidMount () {
        const url = "/api/todolist";
        axios.get(url).then(res => {
            console.log(res.data)
        }).catch(err => console.log(err))
    }

    getTodoItem = () => {
        return this.state.list.map((item, index) => {
            return <TodoItem key={item+index} content={item} index={index} deleteIt={this.deleteIt} />  
        })
    }

    // 更改输入
    handleInputChange = (e) => {
        const inputValue = e.target.value
        this.setState(() => ({ inputValue }))
    }

    // 增加列表项
    addList = () => {
        this.setState((prevState) => ({
            list: [...prevState.list, prevState.inputValue],
            inputValue: ""
        }))
    }

    // 删除项
    deleteIt = (index) => {
        this.setState((prevState) => {
            const list = [...prevState.list];
            list.splice(index, 1);
            return { list };
        })
    }
}
 
export default TodoList;